package com.scl.springtalis.filter;

import com.alibaba.fastjson.JSONObject;
import com.scl.springtalis.polo.Result;
import com.scl.springtalis.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@WebFilter(urlPatterns = "/*")
@Slf4j
public class FilterDemo implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求Url
        String url = request.getRequestURL().toString();
        log.info("获取url:{}", url);

        if (url.contains("login")) {
            log.info("登录方行");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //获取JWT令牌
        String token = request.getHeader("token");

        if (!StringUtils.hasLength(token)) {
            log.info("未登录");
            Result notLogin = Result.error("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(notLogin);
            response.getWriter().write(jsonString);
            return;
        }
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失效");
            Result notLogin = Result.error("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(notLogin);
            response.getWriter().write(jsonString);
            return;
        }
        log.info("放行");
        filterChain.doFilter(servletRequest, servletResponse);
    }


}
